import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpServe {
    private ServerSocket socket=null;
    public TcpServe(int port) throws IOException {
        socket=new ServerSocket(port);
    }
    public void start() throws IOException {
        while(true)
        {
            //使用这个socket1和具体的客户端进行交流
            Socket socket1=socket.accept();
            //客户端在构造Socket对象的时候，就会指定服务器的IP和端口，如果没有客户端来连接，此时accept
            //就会阻塞,也就不会有socket1这个对象
            connection(socket1);
            //使用这个方法来建立一个连接，这个连接对应到一个客户端
        }
    }
    public void connection(Socket socket1) throws IOException {
        System.out.printf("[%s:%d]:客户端上线",socket1.getInetAddress().toString(),socket1.getPort());
              //基于socket对象和客户端进行通信
            try (OutputStream outputStream = socket1.getOutputStream(); InputStream inputStream = socket1.getInputStream(
            )) {
                //处理多个请求和响应，使用循环来进行
                while(true) {
                   //1.读取请求
                    Scanner scan = new Scanner(inputStream);
                    if (!scan.hasNext()) {
                        System.out.printf("[%s:%d]:服务器下线",socket1.getInetAddress().toString(),socket1.getPort());
                        break;
                    }
                    String request = scan.next();//此处的next是一直读取到换行符/空格/其他空白符结束，但是最终返回结果不包括上述空白符
                    //根据请求构造响应
                    String response = process(request);
                    PrintWriter writer = new PrintWriter(outputStream);
                    //使用println来写入，让结果中带有一个\n换行，方便对端来接受解析
                    writer.println(response);
                    //flush用来刷新缓冲区，保证当前写入的数据，发送出去
                    writer.flush();
                    System.out.printf("[%s:%d],res:%s,resp:%s",socket1.getInetAddress().toString(),socket1.getPort(),request,
                            response);
                }



            } catch (IOException e) {
                throw new RuntimeException(e);
            }finally{
                socket1.close();

            }

    }
    public String process(String request)
    {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpServe tcpServe=new TcpServe(10001);
        tcpServe.start();

    }
}
